#!/bin/bash

# Copyright (c) 2023 boomlee.com
# Author: boomlee.com

set -e
source 00_env

# 安装sshpass
function install_sshpass() {
    echo -e "$CSTART>>>>$(hostname -I) [$(date +'%Y-%m-%d %H:%M:%S')]$CEND"
    rpm -Uvh rpms/epel-release-7-14.noarch.rpm || true
    rpm -Uvh rpms/sshpass-1.06-2.el7.x86_64.rpm || true
}

# 配置双向免密（虚拟机 <-> 虚拟机）
function config_sshpass() {
    ##1.在本地为每台机器生成公私钥，把公钥合并到authorized_keys
    cat config/vm_info | grep -v "^#" | grep -v "^$" | while read ipaddr name passwd
    do
        echo -e "$CSTART>>>>$ipaddr>step 1 [$(date +'%Y-%m-%d %H:%M:%S')]$CEND"
        echo n | ssh-keygen -t rsa -q -f "$HOME/.ssh/$name" -C "$name" -N "" || true
        sed -i "/$name/d" $HOME/.ssh/authorized_keys || true
        cat $HOME/.ssh/$name.pub >> $HOME/.ssh/authorized_keys
    done
    
    ##2.把不同的公私钥，分发到不同的服务器
    cat config/vm_info | grep -v "^#" | grep -v "^$" | while read ipaddr name passwd
    do
        echo -e "$CSTART>>>>$ipaddr>step 2 [$(date +'%Y-%m-%d %H:%M:%S')]$CEND"
        sshpass -p $passwd ssh -tt -n -o StrictHostKeyChecking=no $ipaddr "mkdir -p $HOME/.ssh"
        sshpass -p $passwd scp $HOME/.ssh/$name $ipaddr:$HOME/.ssh/id_rsa
        sshpass -p $passwd scp $HOME/.ssh/$name.pub $ipaddr:$HOME/.ssh/id_rsa.pub
        sshpass -p $passwd scp $HOME/.ssh/authorized_keys $ipaddr:$HOME/.ssh/authorized_keys
        sshpass -p $passwd ssh -tt -n -o StrictHostKeyChecking=no $ipaddr "chmod -R 600 $HOME/.ssh"
    done
}

function main() {	
    echo -e "$CSTART>01_sshpass.sh$CEND"

    echo -e "$CSTART>>install_sshpass$CEND"
    install_sshpass

    echo -e "$CSTART>>config_sshpass$CEND"
    config_sshpass
}

main
